package com.hz.controller;

import com.hz.pojo.Result;
import com.hz.pojo.User;
import com.hz.service.UserService;
import com.hz.utils.JwtUtil;
import com.hz.utils.Md5Util;
import com.hz.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}") String username, @Pattern(regexp = "^\\S{5,16}")String password){
        //  查询用户名是否冲突
        User u = userService.findByName(username);
        if (u==null){
            // 不冲突 进行注册
            userService.add(username,password);
            return Result.success();
        }else {
            // 冲突 不予注册
            return Result.error("用户名冲突，不予注册");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}") String username, @Pattern(regexp = "^\\S{5,16}")String password){
        // 查询用户是否存在
        User user = userService.findByName(username);
        if (user==null){
            return Result.error("用户不存在！");
        }
        // 验证用户密码
        if (!Md5Util.checkPassword(password,user.getPassword())) {
            return Result.error("密码错误！");
        }else {
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            String token = JwtUtil.genToken(claims);
            // 把tokens放入redis中
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            ops.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
    }

    @GetMapping("/userInfo")
//    public Result<User> userInfo(@RequestHeader("Authorization")String token){
    public Result<User> userInfo(){
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){  // 映射请求体内容到user  开启User属性规则验证
        user.setUpdateTime(LocalDateTime.now());

        return userService.update(user)==1?Result.success("更新成功！"):Result.error("更新失败！");
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@URL String avatarUrl){
        return userService.updateAvatarUrl(avatarUrl)==1?Result.success("更新成功！"):Result.error("更新失败！");
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization")String token){
        String old_pwd = params.get("old_pwd");
        String new_pwd = params.get("new_pwd");
        String re_pwd = params.get("re_pwd");

        if (!StringUtils.hasLength(old_pwd)&&!StringUtils.hasLength(new_pwd)&&!StringUtils.hasLength(re_pwd)){
            return Result.error("缺少必要的参数");
        }
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByName(username);

        // 先验证旧密码
        if (!Md5Util.checkPassword(old_pwd,user.getPassword())){
            return Result.error("旧密码错误，请重新输入");
        }
        // 再验证新密码是否合法
        if (!new_pwd.equals(re_pwd)){
            return Result.error("两次密码输入不一致，请重新输入");
        }
        // 移除redis中对应的token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        return userService.updatePwd(username,new_pwd)==1?Result.success("更新成功"):Result.error("更新失败");
    }
}
